/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package aiaudio.storage.simple;

import aiaudio.storage.api.RevereUserArtistTuple;
import aiaudio.storage.api.Tuple;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map.Entry;

/**
 *
 * @author Nastya
 */
public class StatisticsLogger {

    private HashMap<RevereUserArtistTuple, Tuple<Double, Double>> results;

    public StatisticsLogger(HashMap<RevereUserArtistTuple, Tuple<Double, Double>> results) {
        this.results = results;
    }

    public void write(String filename) throws FileNotFoundException {
        PrintWriter writer = new PrintWriter(filename);
        String header = String.format("%s %s %s %s %s", "<artist uid>", "<user uid>", "<actual rating>", "<calculated rating>", "<deviation>");
        writer.println(header);
        double max = Double.MIN_VALUE;
        double min = Double.MAX_VALUE;
        double sum = 0;
        int counter = 0;

        for (Entry<RevereUserArtistTuple, Tuple<Double, Double>> entry : results.entrySet()) {
            String artistUID = entry.getKey().getFirst().getUID();
            String userUID = entry.getKey().getSecond().getUID();
            Double actualRating = entry.getValue().getFirst();
            if(actualRating == 0){
                continue;
            }
            Double calculatedRating = entry.getValue().getSecond();
            double error = Math.abs(actualRating - calculatedRating);
            String line = String.format("%s %s %f %f %f", artistUID, userUID, actualRating, calculatedRating, error);
            writer.println(line);
            if(max < error){
                max = error;
            }
            
            if(min > error){
                min = error;
            }
            
            sum += error;
            counter++;
        }
        
        writer.println();
        writer.println();
        writer.println("---------------------------------------------");
        double avg = sum / (double) counter;
        
        writer.println(String.format("Calculated: %d", counter));
        writer.println(String.format("Min deviation: %0$f", min));
        writer.println(String.format("Max deviation: %0$f", max));
        writer.println(String.format("Avg deviation: %0$f", avg));
        writer.flush();
        writer.close();
    }
}
